import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_app_custom_chat/chart/canvas/histogram_chart.dart';
import 'package:flutter_app_custom_chat/chart/chart_enum.dart';

import 'canvas/line_chart.dart';

class ChartView extends StatelessWidget {
  final double height; //控件最大高度
  final List<double> data; //数据
  final double maxY; //y轴最大刻度
  final double padding;
  final double indexWidth; //游标宽度
  final double indexHeight; //游标高度
  final double itemWidth; //柱状图宽度
  final ChartEnum e;

  ChartView(
      {this.height = 200.0,
      this.data,
      this.maxY,
      this.padding = 10,
      this.indexWidth = 15,
      this.indexHeight = 5,
      this.itemWidth = 10,
      this.e = ChartEnum.Line});

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      var width = constraints.maxWidth;

      print('height:$height');

      return Stack(
        children: [
          XyPaint(width, height, padding),
          Container(
            margin: EdgeInsets.only(left: padding),
            child: SingleChildScrollView(
              physics: BouncingScrollPhysics(),
              scrollDirection: Axis.horizontal,
              child: buildWidget(width, e),
            ),
          )
        ],
      );
    });
  }

  // ignore: missing_return
  Widget buildWidget(double width, ChartEnum e) {
    if (e == ChartEnum.Line) {
      return LineChartPaint(width, height, data, maxY, padding, indexWidth,
          isSmooth: true);
    } else if (e == ChartEnum.Histogram) {
      return HistogramChartPaint(
          width, height, data, maxY, padding, indexWidth, itemWidth);
    }
  }
}

class XyPaint extends CustomPaint {
  double width;
  double height;
  double padding;

  XyPaint(this.width, this.height, this.padding);

  @override
  Size get size => Size(width, height);

  @override
  CustomPainter get painter => XyPainter(padding);
}

///x y轴坐标
class XyPainter extends CustomPainter {
  double jWidth = 4;
  double jHeight = 8;
  double padding;

  XyPainter(this.padding);

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..color = Colors.blue
      ..isAntiAlias = true
      ..strokeCap = StrokeCap.round
      ..strokeWidth = 2;

    var point = Offset(padding, size.height - padding);
    var topPoint = Offset(padding, padding);
    var rightPoint = Offset(size.width - padding, point.dy);
    canvas.drawLine(point, rightPoint, paint);
    canvas.drawLine(point, topPoint, paint);

    canvas.drawLine(
        topPoint, Offset(topPoint.dx + jWidth, topPoint.dy + jHeight), paint);
    canvas.drawLine(rightPoint,
        Offset(rightPoint.dx - jHeight, rightPoint.dy - jWidth), paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }
}
